//
//  UIColor+YGHexColor.m
//  UIKit分类整合
//
//  Created by Mr.xu on 2017/1/8.
//  Copyright © 2017年 xuyaguang. All rights reserved.
//

#import "UIColor+YGHexColor.h"

@implementation UIColor (YGHexColor)

CGFloat colorComponentFrom(NSString *string, NSUInteger start, NSUInteger length) {
    NSString *substring = [string substringWithRange:NSMakeRange(start, length)];
    NSString *fullHex = (length == 2) ? substring : [NSString stringWithFormat: @"%@%@", substring, substring];
    
    unsigned hexComponent;
    [[NSScanner scannerWithString:fullHex] scanHexInt: &hexComponent];
    return hexComponent / 255.0;
}


+ (UIColor *)yg_colorWithHexString:(NSString *)hexString {
    return [self yg_colorWithHexString:hexString alpha:1.0f];
}

+ (UIColor *)yg_colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha {
    
    CGFloat a, r, b, g;
    
    NSString *colorString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    if ([hexString hasPrefix:@"#"]) {
        colorString = [colorString substringFromIndex:1];
    }
    if ([hexString hasPrefix:@"0x"]) {
        colorString = [colorString substringFromIndex:2];
    }
    
    switch ([colorString length]) {
        case 3: // #RGB
            a = 1.0f;
            r = colorComponentFrom(colorString, 0, 1);
            g = colorComponentFrom(colorString, 1, 1);
            b = colorComponentFrom(colorString, 2, 1);
            break;
            
        case 4: // #ARGB
            a = colorComponentFrom(colorString, 0, 1);
            r = colorComponentFrom(colorString, 1, 1);
            g = colorComponentFrom(colorString, 2, 1);
            b = colorComponentFrom(colorString, 3, 1);
            break;
            
        case 6: // #RRGGBB
            a = 1.0f;
            r = colorComponentFrom(colorString, 0, 2);
            g = colorComponentFrom(colorString, 2, 2);
            b = colorComponentFrom(colorString, 4, 2);
            break;
            
        case 8: // #AARRGGBB
            a = colorComponentFrom(colorString, 0, 2);
            r = colorComponentFrom(colorString, 2, 2);
            g = colorComponentFrom(colorString, 4, 2);
            b = colorComponentFrom(colorString, 6, 2);
            break;
            
        default:
            return [UIColor blackColor];
    }
    return [UIColor colorWithRed:r green:g blue:b alpha:a];
}



@end
